/**
 * orgId管理组合式函数
 * 处理orgId的获取、存储和管理逻辑
 */

import { getEnvFromUrl } from '~/utils/env';

/**
 * 获取orgId的组合式函数
 */
export const useOrgId = () => {
  // 响应式的orgId状态
  const orgId = useState<string>('orgId', () => '');

  /**
   * 根据环境配置和URL参数获取orgId
   */
  const getOrgId = (): string => {
    // 如果已经有缓存的orgId，直接返回
    if (orgId.value) {
      return orgId.value;
    }

    // 优先从URL参数中获取orgId
    if (process.client) {
      const urlParams = new URLSearchParams(window.location.search);
      const urlOrgId = urlParams.get('orgId');
      if (urlOrgId) {
        // 保存到状态和localStorage
        orgId.value = urlOrgId;
        localStorage.setItem('orgId', urlOrgId);
        return urlOrgId;
      }

      // 从localStorage中获取之前保存的orgId
      const savedOrgId = localStorage.getItem('orgId');
      if (savedOrgId) {
        orgId.value = savedOrgId;
        return savedOrgId;
      }
    }

    // 根据环境配置确定默认orgId
    const env = getEnvFromUrl() || null;

    let defaultOrgId: string;
    if (!env) {
      defaultOrgId = '340';
    } else if (env.startsWith('box')) {
      defaultOrgId = '169';
    } else if (env.startsWith('qc')) {
      defaultOrgId = '10';
    } else {
      defaultOrgId = '340';
    }

    orgId.value = defaultOrgId;
    return defaultOrgId;
  };

  /**
   * 设置orgId
   */
  const setOrgId = (newOrgId: string) => {
    orgId.value = newOrgId;
    if (process.client) {
      localStorage.setItem('orgId', newOrgId);
    }
  };

  /**
   * 清除orgId
   */
  const clearOrgId = () => {
    orgId.value = '';
    if (process.client) {
      localStorage.removeItem('orgId');
    }
  };

  /**
   * 监听URL变化，自动更新orgId
   */
  const watchUrlOrgId = () => {
    if (process.client) {
      const route = useRoute();
      watch(
        () => route.query.orgId,
        newOrgId => {
          if (newOrgId && typeof newOrgId === 'string') {
            setOrgId(newOrgId);
          }
        },
        { immediate: true }
      );
    }
  };

  return {
    orgId: readonly(orgId),
    getOrgId,
    setOrgId,
    clearOrgId,
    watchUrlOrgId,
  };
};
